package com.batdream.message.service.impl;

import com.batdream.message.pojo.Users;
import com.batdream.message.pojo.bo.UserBo;
import com.batdream.message.pojo.vo.UserVo;
import com.batdream.message.service.FileService;
import com.batdream.message.service.UserService;
import com.batdream.message.utils.FastDFSClient;
import com.batdream.message.utils.FileUtils;
import com.batdream.message.utils.JSONResult;
import com.batdream.message.utils.SpringContextUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author Wang Chen Peng
 * @date 2018/12/26
 * describe:
 */
@Service
@Log4j2
public class FileServiceImpl implements FileService, ApplicationListener<ContextRefreshedEvent> {

    private final FastDFSClient fastDFSClient;

    private UserService userService;

    @Autowired
    public FileServiceImpl(FastDFSClient fastDFSClient) {
        this.fastDFSClient = fastDFSClient;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        userService = contextRefreshedEvent.getApplicationContext().getBean(UserService.class);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public JSONResult uploadBase64(UserBo userBo) {
        log.debug("上传头像 入参 :{}", userBo);
        if (StringUtils.isEmpty(userBo.getData())) {
            log.debug("上传头像 上传的图片为空 参数 : {}", userBo);
            return JSONResult.errorMsg("上传的图片不能为空");
        }
        if (StringUtils.isEmpty(userBo.getUserId())) {
            log.debug("上传头像 上传的id为空 参数 : {}", userBo);
            return JSONResult.errorMsg("用户id不能为空");
        }

        String separator = System.getProperty("file.separator");
        String path = null;
        String fileName = UUID.randomUUID().toString() + userBo.getUserId() + ".png";
        //根据代码运行系统 进行设置swap路径
        if ("\\".equals(separator)) {
            path = "D:\\software\\swap" + separator + fileName;
        } else {
            path = "/usr/local/upload/swap" + separator + fileName;
        }
        log.debug("上传图片 暂存路径为 : {}", path);

        try {
            FileUtils.base64ToFile(path, userBo.getData());
        } catch (Exception e) {
            return JSONResult.errorMsg("图片暂存到磁盘swap错误");
        }
        MultipartFile multipartFile = FileUtils.fileToMultipart(path);

        String saveBigImgUrl;
        try {
            saveBigImgUrl = fastDFSClient.uploadBase64(multipartFile);
        } catch (IOException e) {
            return JSONResult.errorMsg("图片上传到文件服务器错误");
        }
        String[] arr = saveBigImgUrl.split("\\.");
        String saveMicroImgUrl = arr[0] + "_80x80." + arr[1];
        log.debug("上传图片 图片服务器链接 大图 : {} , 小图 : {}", saveBigImgUrl, saveMicroImgUrl);
        //更新用户数据
        int updateNumber = userService.updateUserImg(userBo.getUserId(), saveBigImgUrl, saveMicroImgUrl);
        log.debug("上传图片 更新用户资料 更新条数 : {}", updateNumber);
        Users users = userService.queryUserById(userBo.getUserId());
        log.debug("上传图片 上传图片完成 返回结果 : {}", users);
        return JSONResult.ok(users);
    }

    @Override
    public String getPathByUserId(String id) {
        String separator = System.getProperty("file.separator");
        String path = null;
        String fileName = UUID.randomUUID().toString() + id + ".png";
        //根据代码运行系统 进行设置swap路径
        if ("\\".equals(separator)) {
            path = "D:\\software\\swap" + separator + fileName;
        } else {
            path = "/usr/local/upload/swap" + separator + fileName;
        }
        return path;
    }

    @Override
    public String saveImgByPath(String path) {

        //根据path获取multipartFile
        MultipartFile multipartFile = FileUtils.fileToMultipart(path);

        String saveBigImgUrl;
        try {
            saveBigImgUrl = fastDFSClient.uploadBase64(multipartFile);
        } catch (IOException e) {
            return null;
        }
        return saveBigImgUrl;
    }


}
